package com.example.sunray.bluetooth.SSP;

import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangjianqiang on 2018/7/12 10:26.
 * Package name com.example.sunray.bluetooth.SSP
 */
public class DataBean {
    public static List<DataBean> unFinisedList;
    long fileLength = 0;
    String path = "";
    FileOutputStream outputStream = null;
    File file = null;

    public DataBean(long fileLength) {
        if (unFinisedList == null) {
            unFinisedList = new ArrayList<>();
        }
        this.fileLength = fileLength;
        creatFile();
    }


    public long getFileLength() {
        return fileLength;
    }

    public void setFileLength(int fileLength) {
        this.fileLength = fileLength;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    private void creatFile() {
        File parent = new File(Environment.getExternalStorageDirectory() + "/" + "Receive/");
        if (!parent.exists()) {
            parent.mkdir();
        }
        file = new File(Environment.getExternalStorageDirectory() + "/" + "Receive/" + System.currentTimeMillis() + ".jpg");
        path = file.getPath();
        try {
            outputStream = new FileOutputStream(file);
        } catch (Exception e) {

        }
    }

    /**
    return is this file completed
     */
    public boolean write(byte[] content) {
        try {
            if (fileLength <= file.length()) {
                return true;
            }
            outputStream.write(content);
            outputStream.flush();
            if (fileLength <= file.length()) {
                return true;
            }
        } catch (Exception e) {

        }
        return false;
    }

    public void cancle() {
        if (file == null) {
            if (path == null) {
                return;
            }
            file = new File(path);
        }
        if (file.exists()) {
            if (file.length() == fileLength) {
                return;
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (Exception e) {

            }
        }
        if (file != null) {
            file.delete();
        }
    }

    public static void deleteUnFinishedFile() {
        if (unFinisedList != null && unFinisedList.size() > 0) {
            for (int i = 0; i < unFinisedList.size(); i++) {
                unFinisedList.get(i).cancle();
            }
            unFinisedList.clear();
        }
    }
}
